import Vue from 'vue';
import { submitOrder } from '@/api/applet';

let VideoAd = null;
let VideoAdId = '';
/**
 * 初始化视频广告
 * callbackFn 观看完回调函数
 */
function initVideoAd(callbackFn) {
  const that = this;
  VideoAdId = Vue.prototype.$store.state.appletInfo.video_ad; // 激励视频广告id
  if (uni.createRewardedVideoAd && VideoAdId) {
    // #ifdef MP-QQ || MP-WEIXIN
    VideoAd = uni.createRewardedVideoAd({
      adUnitId: VideoAdId
    });
    // #endif

    // #ifdef MP-KUAISHOU
    VideoAd = uni.createRewardedVideoAd({
      type: '13001',
      adUnitId: VideoAdId
    });
    // #endif

    // 加载视频
    VideoAd.onLoad(function(data){
      console.log(data);
    })

    // 进行适当的提示--捕捉错误
    VideoAd.onError(err => {
      VideoAd.load();
      // that.createCartoon();
    });

    // 监听关闭
    VideoAd.onClose((status) => {
      if (status && status.isEnded || status === undefined) {
        // 观看完回调函数
        callbackFn();
      } else {
        uni.showToast({
          title: '播放完成才可以下载哦~',
          icon: 'none',
          duration: 5 *1000
        });
        VideoAd.load();
      }
    })
  }
}

// 播放激励视频广告
function payVideoAd() {
  VideoAd.show();
}

// 创建订单信息
function createOrder(params) {
  submitOrder(params);
}

// 初始化插屏广告
let InterstitialAd = null;
function initInterstitialAd() {
  const that = this;
  const interstitialAdId = Vue.prototype.$store.state.appletInfo.interstitial_ad; // 激励视频广告id
  InterstitialAd = uni.createInterstitialAd({
    adUnitId: interstitialAdId
  });
  InterstitialAd.load().catch((err) => {
    console.error('load',err)
  })        
  InterstitialAd.onLoad(() => {
    console.log('onLoad event emit') 
  })
  InterstitialAd.onClose(() => {
    console.log('close event emit')
  })       
  InterstitialAd.onError((e) => {
    console.log('error', e)
  }) 
}

// 显示插屏广告
function displayInterstitialAd() {
  InterstitialAd.show().catch((err) => {
    console.error('show',err)
  });
  setTimeout(() => {
    InterstitialAd.load().catch((err) => {
      console.error('load',err)
    }, 800);
  })
}

module.exports = {
  initVideoAd,
  payVideoAd,
  createOrder,
  initInterstitialAd,
  displayInterstitialAd
}
